import axios from 'axios'
import { ElMessage } from 'element-plus'
const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'
import { useUserStore } from "@/stores/userStore.js"   //获取存的方法
import router from '@/router';


//连接的后端地址 
const URL = "http://pcapi-xiaotuxian-front-devtest.itheima.net"
// 创建axios实例
const service = axios.create({
    baseURL: `${URL}`,
    timeout: 5000
})
// request请求拦截器    
service.interceptors.request.use(req => {
    // console.log(req);
    const userStore = useUserStore()//赋值给变量
    const token = userStore.userInfo.token ?? ''
    //判断token
    if (token) {
        req.headers.Authorization = `Bearer ${token}`
    }

    return req
}, error => {
    return Promise.reject(error)
})

// respone响应拦截器
service.interceptors.response.use(res => {
    if (res?.status === 200) {
        return res.data
    }
    return Promise.reject(TOKEN_INVALID)
}, error => {
    ElMessage.error(error.response.data.message)
    // console.log(error);
    const userStore = useUserStore()//赋值给变量
    if (error.response.status == 401) {
        router.push({ path: '/login' })
        userStore.clearUserInfo()
    }
})

export default service